package com.guomao.down;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/down")
public class Download extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取应用程序上下文对象
        ServletContext sc = getServletContext();
        String realPath = sc.getRealPath("/files/测试 123.txt");
//        System.out.println(realPath);
//        D:\guomaolesson\Java2411\03-javaweb-fileupdown\src\main\webapp\files\测试 123.txt
        File file = new File(realPath);
        if (!file.exists()) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
            return;
        }
        String mimeType = sc.getMimeType(realPath);
//        System.out.println(mimeType);//text/plain
        resp.setContentType(mimeType != null ? mimeType : "application/octet-stream");
        String name = file.getName();
        String final_name = URLEncoder.encode(name, "UTF-8").replace("+", "%20");
        resp.setHeader("Content-Disposition",
                "attachment; filename*=UTF-8''" + final_name);
        IOUtils.copy(new FileInputStream(file), resp.getOutputStream());
    }
}
